<template>
  <div class="questionnaire">
    <h1>心理健康测试</h1>

    <!-- 答题卡 -->
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step v-for="(question, index) in questions" :key="question.tid" :title="'题目 ' + (index + 1)">
        <template #description>
          <span @click="jumpToQuestion(index)" style="cursor: pointer; color: blue;">
            {{ isAnswered(index) ? '已回答' : '未回答' }}
          </span>
        </template>
      </el-step>
    </el-steps>

    <!-- 当前题目展示 -->
    <div v-if="activeStep < questions.length" class="question-section">
      <h2>{{ currentQuestion.description }}</h2> <!-- 显示题目内容 -->
      <div class="answers">
        <el-button
            v-for="(answer, index) in possibleAnswers"
            :key="index"
            type="primary"
            size="medium"
            @click="handleAnswer(answer)"
            :disabled="answer.selected"
        >
          {{ answer.text }} ({{ answer.score }}分) - {{ answer.topic }}
        </el-button>
      </div>

      <!-- 下一题按钮 -->
      <div v-if="currentAnswer !== null">
        <el-button type="success" size="large" @click="nextQuestion">下一题</el-button>
      </div>
    </div>

    <!-- 结果页面 -->
    <div v-else class="result-section">
      <h2>测试完成！</h2>
      <p>您的总分是：<strong>{{ totalScore }}</strong></p>
      <p>根据您的得分，您可能处于以下心理健康状态：</p>
      <p><strong>{{ mentalHealthStatus }}</strong></p>
      <el-button type="success" size="large" @click="resetQuiz">重新开始</el-button>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      activeStep: 0, // 当前题目索引，从 0 开始
      questions: [], // 题目列表，从后端动态获取
      totalScore: 0, // 用户累计得分
      currentAnswer: null, // 当前题目的答案
      loading: true, // 是否正在加载
    };
  },
  computed: {
    currentQuestion() {
      const question = this.questions[this.activeStep] || {};
      console.log("当前题目:", question); // 打印当前题目
      return question;
    },
    possibleAnswers() {
      // 使用 computed 属性来确保每次切换题目时都更新 possibleAnswers
      const question = this.currentQuestion;
      return question ? question.options || [] : [];
    },
    mentalHealthStatus() {
      // 根据总分返回对应的心理健康状态
      if (this.totalScore <= 20) {
        return '重度抑郁';
      } else if (this.totalScore <= 49) {
        return '中度抑郁';
      } else if (this.totalScore <= 59) {
        return '轻度抑郁';
      } else {
        return '正常';
      }
    }
  },
  methods: {
    // 获取题目数据
    async fetchQuestions() {
      try {
        const response = await axios.get("/api/question/getAllQuestions");
        console.log("API 返回数据:", response.data);  // 打印返回的数据

        if (!response.data || response.data.code !== 200) {
          this.$message.error(response.data?.message || '无法获取题目');
          return;
        }

        this.questions = response.data.items.map(item => ({
          ...item,
          options: []
        }));  // 更新题目数据并初始化 options 为空数组

        // 获取每个题目的选项
        for (const question of this.questions) {
          try {
            const optionsResponse = await axios.get(`/api/topicSelect/options/${question.tid}`); // 确保使用正确的 tid
            console.log(`获取选项响应（题目ID: ${question.tid}）：`, optionsResponse.data);

            if (
                !optionsResponse.data ||
                optionsResponse.data.code !== 200 ||
                !optionsResponse.data.data
            ) {
              console.error(
                  `获取选项失败（题目ID: ${question.tid}）：`,
                  optionsResponse.data?.message || '未知错误'
              );
              question.options = []; // 设置为空数组避免后续错误
              continue;
            }

            question.options = optionsResponse.data.data.map(option => ({
              text: option.tselect,
              score: option.tscore,
              topic: option.topic, // 添加主题字段
              selected: false // 标记是否已选择
            }));
          } catch (error) {
            console.error(`获取选项失败（题目ID: ${question.tid}）：`, error);
            question.options = []; // 设置为空数组避免后续错误
          }

          console.log(`选项数据更新后（题目ID: ${question.tid}）：`, question.options);  // 打印更新后的选项数据
        }

        this.loading = false;  // 停止加载中状态
      } catch (error) {
        console.error("获取题目失败：", error);
        this.$message.error("无法加载题目，请稍后重试");
      }
    },

    // 初始化题目
    setCurrentQuestion() {
      if (this.questions.length > 0) {
        this.activeStep = 0; // 重置为第一题
        this.totalScore = 0; // 重置分数
        this.currentAnswer = null; // 清空答案
        this.questions.forEach(question => {
          question.options.forEach(option => {
            option.selected = false;
          });
        });
      }
    },

    // 处理答案选择
    handleAnswer(answer) {
      this.currentAnswer = answer.text;
      // 计算分数，根据当前题目和选项来累加分数
      this.totalScore += answer.score || 0; // 使用选项中的分数，避免 null 或 undefined
      // 标记选项为已选择
      this.currentQuestion.options.forEach(option => {
        option.selected = option.text === answer.text;
      });
    },

    // 切换到下一题
    nextQuestion() {
      // 只有在答完题目之后，才切换到下一题
      if (this.activeStep < this.questions.length - 1) {
        this.activeStep++; // 下一题
        this.currentAnswer = null; // 重置当前答案
      } else {
        this.activeStep++; // 完成所有题目后，显示结果页面
      }
    },

    // 重新开始测试
    resetQuiz() {
      this.setCurrentQuestion(); // 重新开始
    },

    // 跳转到指定题目
    jumpToQuestion(index) {
      this.activeStep = index;
      this.currentAnswer = this.questions[index].options.find(option => option.selected)?.text || null;
    },

    // 判断某个题目是否已回答
    isAnswered(index) {
      return this.questions[index]?.options.some(option => option.selected);
    }
  },
  created() {
    this.fetchQuestions(); // 页面加载时获取题目
  },
};
</script>
<style scoped>
.questionnaire {
  max-width: 600px;
  margin: 20px auto;
  text-align: center;
}
.answers {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}
.result-section {
  margin-top: 40px;
}
.el-step__description {
  cursor: pointer;
  color: blue;
}
</style>